<template>
  <div class="editor-3d_wrapper">
    <!-- 头部区域 -->
    <Header></Header>
    <!-- 主体区域 -->
    <div class="editor-threejs_3d" :class="bgc" id="editor-threejs_3d">
      <!-- :style="{ height: height + 'px', width: width + 'px' }" -->
    </div>
    <MenuNav v-if="isShowPanel"></MenuNav>
    <PanelLeft v-if="isShowPanel"></PanelLeft>
    <PanelRight v-if="isShowPanel"></PanelRight>
    <ToolsBox v-if="isShowPanel"></ToolsBox>
  </div>
</template>

<script>
import Header from "./Header.vue";
import MenuNav from "./components/menu/index.vue";
import PanelLeft from "./panelLeft/index.vue";
import PanelRight from "./panelRight/index.vue";
import ToolsBox from "./components/toolsBox/index.vue";
import { senceData, modelsList, iconLists } from "./data/data.js";
import { webglOBJ } from "./utils/webGL/webGL.js";
import { ViewHelper } from "./utils/webGL/ViewHelper.js";

import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
export default {
  components: { Header, MenuNav, PanelLeft, PanelRight, ToolsBox },
  data() {
    return {
      bgc: "lucency",
      width: 1366,
      height: 800,
      isShowPanel: true, // 面板默认是关闭的
      senceData, // 场景数据包
      isShowLabel: true, // 是否显示数据标签
      model: null, //模式
      isShowXyzHelper: true, // xyz辅助线
    };
  },
  async mounted() {
    await this.getView();
    this.pageInt();
  },
  methods: {
    // 设置宽高
    getView() {
      this.height = document.body.clientHeight - 64;
      this.width = document.body.clientWidth;
    },
    pageInt() {
      window.$WEBGL = {}; // webgl存储对象
      window.$WEBGL.editor3D = this;

      // const model = this.$route.query.model; // edit 编辑模式，add 新增模式，detai 详情模式
      this.model = "add"; // edit 编辑模式，add 新增模式，detai 详情模式
      // const id = this.$route.query.id;

      // 编辑
      if (this.model == "edit") {
        // this.getSenceData(id);
        // this.isShowDevLabel = true;
        // this.isShowPanel = true;
      } else if (this.model == "add") {
        // 新增
        this.init(this.senceData);
        this.isShowPanel = true;
      } else {
        // 详情
        // this.getSenceData(id || this.mapId);
        // this.isShowDevLabel = true;
        // this.isShowPanel = false;
      }
    },
    // 加载3D模型
    add3DModle(obj) {
      const empObj = JSON.parse(JSON.stringify(obj));

      // 场景中的灯光加载
      if (empObj.userData.type == "light") {
        empObj.userData.addFunction &&
          lightBox.methods[empObj.userData.addFunction](false);
      }

      const gltf = empObj.userData.url;
      if (!gltf) return;
      const loader = new GLTFLoader();
      // const $loading = startLoading();
      const obs = [];

      loader.load(gltf, (gltf) => {
        let object = gltf.scene;
        // object.material.color.setHex( 0x00ff00 );
        // 遍历元素添加对应阴影效果
        object.traverse((v) => {
          if (v.isMesh) {
            // v.fog = false; // 材质雾化效果
            // v.castShadow = true; // 生成阴影
            // v.receiveShadow = true; // 接受阴影
            // v.material.wireframe = true;
            obs.push(v);
          }
        });

        object.name = empObj.name;
        object.scale.set(empObj.scale.x, empObj.scale.y, empObj.scale.z);
        object.position.set(empObj.position.x, empObj.position.y, empObj.position.z);
        object.rotation.set(empObj.rotation.x, empObj.rotation.y, empObj.rotation.z);
        this.scene.add(object);
      });
    },
    // 灯光
    addAmbientLight() {
      const light = new THREE.AmbientLight(0xfffff); // 柔和的白光
      this.scene.add(light);
    },
    // 鼠标滚动时间
    mousewheelEvent() {
      let scrollNumer = 0; // 滚动计数
      const max = 15;
      const min = 0;
      const dom = document.querySelector(".editor-threejs_3d canvas");
      dom.addEventListener("mousewheel", (evt) => {
        // 当滑轮向上滚动时
        if (evt.wheelDelta > 0) {
          if (scrollNumer < max) {
            scrollNumer++;
            // this.controls.enabled = true;
          } else {
            scrollNumer = 30;
            // this.controls.enabled = false;
          }
          console.log("鼠标向下滚动", scrollNumer);
        } else {
          if (scrollNumer > min) {
            scrollNumer--;
            // this.controls.enabled = true;
          } else {
            scrollNumer = 0;
            // this.controls.enabled = false;
          }
          console.log("鼠标向下滚动", scrollNumer);
        }
      });
    },
    // 创建threejs对象
    init(senceData) {
      if (!senceData) return;
      var vm = this;
      let mixer = null;

      // 初始化场景
      const loader = new GLTFLoader();
      const webGLdom = document.getElementById("editor-threejs_3d");
      const scene = webglOBJ.createSence(webGLdom);

      // 初始化相机
      const camera = webglOBJ.createCamera({
        ...senceData.camera,
        fov: 45,
        aspect: 1,
        near: 0.1,
        far: 2500,
      });
      // 初始化渲染器
      const renderer = webglOBJ.createRenderer(0x000000);
      // 画布大小
      renderer.setSize(this.width, this.height);
      // webglOBJ.createRoomEnvironment(); // 创建房间效果

      // vm.viewHelper = new ViewHelper(camera, webGLdom);

      // 鼠标滚动轨道
      const controls = webglOBJ.createControls();

      // 中心坐标线
      const axisHelper = webglOBJ.createAxisHelper();

      this.mousewheelEvent();

      // 滚动缩小获取比例
      controls.addEventListener("change", (evt) => {
        const max = 1000;
        const min = 0.5;
        const cameraLookAt = evt.target.target; // 移动变化的时候相机的焦点位置
        const cameraPosition = evt.target.object.position; // 移动变化的时候相机的位置
        const distance = cameraPosition.distanceTo(cameraLookAt); // 计算相机的当前位置和焦点位置的距离，从而判断场景视角的缩放
        // console.log('相机位置和焦点的距离', distance);
        if (distance < max && distance > min) {
          this.isShowLabel = true; // 符合区间逻辑
        } else {
          this.isShowLabel = false; // 超出区间逻辑
        }
      });

      this.scene = scene;
      this.controls = controls;
      this.camera = camera;
      this.renderer = renderer;

      // 编辑模式下辅助线显示
      if (["edit", "add"].includes(this.model)) {
        axisHelper.visible = true;
        this.isShowXyzHelper = true;
      } else {
        axisHelper.visible = false;
        this.isShowXyzHelper = false;
      }

      // 将对象添加到场景中去
      webglOBJ.senceAdd([controls, axisHelper]);
      function render() {
        requestAnimationFrame(render);
        vm.renderer.render(vm.scene, vm.camera);
      }
      render();
    },
  },
};
</script>
<style lang="scss">
.editor-3d_wrapper {
  min-width: 1366px;
  height: 100vh;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  background-color: #171d28;
  .editor-threejs_3d {
    width: 100%;
    height: calc(100vh - 64px);
    background-image: url("~assets/3d_icon/edit/mapbg_1.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    position: relative;
  }
  .lucency {
    background-image: url("~assets/3d_icon/edit/mapbg_1.png");
  }
  .day {
    background-image: url("~assets/3d_icon/edit/mapbg_2.png");
  }
  .atdusk {
    background-image: url("~assets/3d_icon/edit/mapbg_3.png");
  }
  .dusk {
    background-image: url("~assets/3d_icon/edit/mapbg_4.png");
  }
}
</style>
